import 'package:auto_route/auto_route.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/recipe/data/model/recipe_module_content_model.dart';
import 'package:casdon/modules/recipe/data/model/recipe_module_model.dart';
import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';

import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:casdon/modules/recipe/ui/widgets/Recipe_card_item.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class RecipeCollectListScreen extends ConsumerStatefulWidget {
  final String modelId;
  final String title;
  final RecipeModuleStyle style;

  const RecipeCollectListScreen({
    super.key,
    required this.modelId,
    required this.title,
    required this.style,
  });

  @override
  ConsumerState<RecipeCollectListScreen> createState() =>
      _RecipeCollectListState();
}

class _RecipeCollectListState extends ConsumerState<RecipeCollectListScreen> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final contentState = ref.watch(
      recipeModuleContentAsyncProvider(widget.modelId),
    );
    final contentNotifier = ref.watch(
      recipeModuleContentAsyncProvider(widget.modelId).notifier,
    );
    final double bottomPadding = MediaQuery.of(context).padding.bottom + 5.h;

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      appBar: CommonAppBar(title: widget.title),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            // contentNotifier.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            await contentNotifier.refresh();
          },
          child: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(child: SizedBox(height: 12.h)),
              contentState.when(
                loading: () => _buildSliverLoading(),
                error: (e, _) => _buildSliverError(''),
                data: (data) {
                  final items = data.data;
                  if (items.isEmpty) {
                    return _buildSliverEmpty('暂无收藏');
                  }
                  return SliverPadding(
                    padding: EdgeInsets.only(left: 12.w, right: 12.w),
                    sliver: SliverGrid(
                      delegate: SliverChildBuilderDelegate((context, index) {
                        return GestureDetector(
                          onTap: () => {
                            _handleItemClick(items[index]),
                          }, // 点击事件写在外面
                          child: buildItem(context, items[index]), // UI 独立封装
                        );
                      }, childCount: items.length),
                      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 200.w,
                        mainAxisSpacing: 12.w,
                        crossAxisSpacing: 12.w,
                        mainAxisExtent: 200.h,
                      ),
                    ),
                  );
                },
              ),
              SliverToBoxAdapter(child: SizedBox(height: bottomPadding)),
            ],
          ),
        ),
      ),
    );
  }

  // ========= 通用状态 Sliver =========
  SliverToBoxAdapter _buildSliverLoading() => const SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: CommonLoadingWidget()),
    ),
  );

  SliverToBoxAdapter _buildSliverError(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: Text(message)),
    ),
  );

  SliverToBoxAdapter _buildSliverEmpty(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(
        child: Text(
          message,
          style: TextStyle(fontSize: 14.r, color: Colors.grey),
        ),
      ),
    ),
  );

  Widget buildItem(BuildContext context, RecipeCardData item) {
    return Container(
      width: 170.w,
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Stack(
          children: [
            /// 背景图片
            CachedNetworkImage(
              imageUrl: item.imgUrl,
              cacheKey: item.imgUrl,
              fit: BoxFit.cover,
              width: double.infinity,
              height: double.infinity,
              fadeInDuration: Duration.zero,
              placeholder: (context, url) => const SizedBox(),
              errorWidget: (context, url, error) {
                return Image.network(
                  recipePlaceHolderImgUrl,
                  fit: BoxFit.cover,
                  width: double.infinity,
                  height: double.infinity,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      color: Colors.grey[200],
                      child: const Icon(
                        Icons.image_outlined,
                        color: Colors.grey,
                      ),
                    );
                  },
                );
              },
            ),

            /// 整体半透明蒙层（覆盖整个图片）
            Container(
              width: double.infinity,
              height: double.infinity,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.black.withAlpha(0), // 顶部轻微遮罩
                    Colors.black.withAlpha(255), // 底部更深
                  ],
                ),
              ),
            ),

            /// 底部文字区域
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      item.title,
                      style: context.textTheme.labelLarge!.copyWith(
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 2.h),
                    Text(
                      '共${item.count}道菜',
                      style: context.textTheme.bodySmall!.copyWith(
                        color: Colors.white.withAlpha(152),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _handleItemClick(RecipeModuleContentModel item) {
    RecipeListRoute(recipeCollectId: item.id, title: item.title).push(context);
  }
}
